<?php
/**
 *
 * Author:苏光盼
 * Date:2020/6/24 下午4:02
 * Class:Pri.php
 * Web:https://app.admin.suanzisu.com
 * Project:通用APP后台管理系统
 *
 */

namespace App\HttpController\Admin;


use App\Logic\Pri as PriLogic;
use App\Model\Adm;
use App\Model\Privileges;
use App\Util\Common;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Http\Exception\Exception as HttpExc;
use EasySwoole\ORM\Exception\Exception;

class Pri extends Base
{
    /**
     * 列出所有权限
     */
    public function admin()
    {
        $data = PriLogic::pris($this->request());
        return $this->lay($data['data'],$data['rows']);
    }

    /**
     * @return mixed
     * @throws Exception
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \Throwable
     * 保存一个权限
     */
    public function save()
    {
        $ret = PriLogic::save($this->request());
        if( $ret ){
            return $this->success(['data'=>$ret]);
        }
        throw new HttpExc('没变化的数据或有重复url',405);
    }

    /**
     * @return mixed
     * @throws Exception
     * @throws \Throwable
     * 重建我的权限缓存 for redis
     */
    public function build_my_pris()
    {
        $md5_uid = $this->request()->getHeaderLine('x-token');
        TaskManager::getInstance()->async(function () use ($md5_uid){
            $uid = \App\Logic\Login::getUserData($md5_uid,'id');
            $adm = Adm::create()->get($uid);
            \App\Logic\Login::setPri($adm);
        });
        return $this->success();
    }


    /**
     * @return mixed
     * @throws Exception
     * @throws \Throwable
     * 删除一个后台权限
     */
    public function del_admin_pri()
    {
        $id = Common::check($this->request());
        $mode = Privileges::create()->get($id);
        if($mode) $mode->destroy();
        else throw new HttpExc('参数错误！',403);
        $this->success();
    }


    /**
     * @throws Exception
     * @throws \Throwable
     * 获取我这个组不拥有的权限
     */
    public function has_nt_pri()
    {
        $group_id =  (int)Common::check($this->request());
        if(!$group_id) throw new HttpExc('参数错误，没有获取到要操作的用户组ID',403);
        $key = $this->request()->getQueryParam('key');
        $limit = Common::limit($this->request());
        $data = PriLogic::getGroupPri($group_id,false,$limit,$key);
        return $this->lay($data['data'],$data['rows']);

    }

    /**
     * @throws Exception
     * @throws \Throwable
     * 获取我这个组所拥有的权限
     */
    public function has_pri(){
        $group_id =   Common::check($this->request());
        $limit = Common::limit($this->request());
        $key = $this->request()->getQueryParam('key');
        $data = PriLogic::getGroupPri($group_id,true,$limit,$key);
        return $this->lay($data['data'],$data['rows']);
    }

}